/**
 *  异步搜索框, 支持搜索结果多选
 *  2021/09/15
 */

import React, { forwardRef, useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import { fetch } from '../../../common/api';
import { log } from '../../../common/tool';

import { Divider, Row, Col, Input, List, message } from 'antd';

const { Search } = Input;
const ListItem = List.Item;

const AjaxInputSearch = forwardRef((props, ref) => {
    const {
        value,
        apiPath,
        apikeyWord,
        urls,
        apiData,
        apiMethod,
        isSearchBtn,
        isdropDown,
        selectItemName,
        onChange,
        onSelect,
        getSearchList,
        onVerifyVal,
    } = props;
    const [loading, setloading] = useState(false);
    const [open, setOpen] = useState(false);
    const [isHover, setHover] = useState(false); // 鼠标移入
    const [dropDownList, setDropDownList] = useState([]);
    let timeout = null;
    // 请求下拉菜单
    const getDropDownList = (keyWord) => {
        setloading(true);
        const queryParms = {};
        queryParms[apikeyWord] = keyWord;
        fetch({
            urls,
            apiPath,
            apiData: {
                ...apiData,
                ...queryParms,
            },
            apiMethod,
        })
            .then((res) => {
                const datas = res && res.data ? res.data : [];
                setDropDownList(datas);
                setTimeout(() => {
                    setloading(false);
                }, 500);
                getSearchList && getSearchList(datas);
            })
            .catch((err) => {
                setloading(false);
                log.error(err);
                message.error(`获取失败:${err.message}`);
            });
    };
    // 值变化
    const searchOnChange = (e) => {
        let val = e.target.value;
        val = val.trim();
        if (onVerifyVal && !onVerifyVal(val)) return;
        onChange && onChange(val);
        if (isSearchBtn) return;
        if (!val) {
            setDropDownList([]);
            setOpen(false);
        } else {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            timeout = setTimeout(() => {
                getDropDownList(val);
            }, 300);
            setOpen(true);
        }
    };
    // 搜索
    const searchOnSearch = (selectVal) => {
        if (selectVal) {
            onChange && onChange(selectVal);
            getDropDownList(selectVal);
            setOpen(true);
        } else {
            setDropDownList([]);
            setOpen(false);
        }
    };
    // 下拉菜单选中
    const searchOnSelect = (selectVal, index) => {
        const newList = JSON.parse(JSON.stringify(dropDownList));
        newList.forEach((item) => {
            item.active = item[selectItemName] === selectVal[selectItemName];
        });
        setDropDownList(newList);
        onSelect && onSelect(selectVal, index);
        onChange && onChange(selectVal[selectItemName]);
        setOpen(false);
    };
    // 获取焦点
    const searchOnFocus = () => {
        if (isdropDown && value) {
            if (!dropDownList || dropDownList.length < 1) {
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
                timeout = setTimeout(() => {
                    getDropDownList(value);
                }, 300);
            }
            setOpen(true);
        }
    };
    // 失去焦点
    const searchOnBlur = () => {
        if (!isHover) {
            setOpen(false);
        }
    };

    let defaultProps = {};
    if (isSearchBtn) {
        defaultProps = {
            enterButton: '搜索',
            onSearch: searchOnSearch,
        };
    }
    return (
        <div ref={ref} className="ajax-input-search">
            <div>
                <Search
                    {...defaultProps}
                    allowClear
                    placeholder="请输入"
                    onChange={searchOnChange}
                    onFocus={searchOnFocus}
                    onBlur={searchOnBlur}
                    value={value}
                />
            </div>
            <div
                className="search-drop-down"
                style={{ display: isdropDown && open ? 'block' : 'none' }}
                onMouseOver={() => setHover(true)}
                onMouseOut={() => setHover(false)}
            >
                <List
                    loading={loading}
                    locale={{
                        emptyText: '暂无数据',
                    }}
                    split={false}
                    size="small"
                    className="drop-down-list"
                    dataSource={dropDownList}
                    renderItem={(item) => (
                        <ListItem
                            className={item.active ? 'drop-down-item-active drop-down-item' : 'drop-down-item'}
                            onClick={() => searchOnSelect(item)}
                        >
                            {selectItemName ? item[selectItemName] : item}
                        </ListItem>
                    )}
                />
            </div>
        </div>
    );
});
// function AjaxInputSearch (props) {

// }

AjaxInputSearch.defaultProps = {
    apiData: {},
    apiMethod: 'GET',
    isSearchBtn: false,
    isdropDown: true,
};

AjaxInputSearch.propTypes = {
    apiPath: PropTypes.string.isRequired, // API接口
    apiData: PropTypes.object, // 附加产参数
    apiMethod: PropTypes.string, // api请求method
    apikeyWord: PropTypes.string.isRequired, // 查询参数key
    value: PropTypes.string, // api请求method
    selectItemName: PropTypes.string.isRequired, // 下拉菜单展示的键值名
    isSearchBtn: PropTypes.bool, // 是否显示搜索按钮，显示后输入值不查询，需点击查询
    isdropDown: PropTypes.bool, // 是否显示下拉菜单
    onVerifyVal: PropTypes.func, // 验证值，返bool , true，查询， false 停止
    onSelect: PropTypes.func, // 下拉框选中值
    getSearchList: PropTypes.func, // 查询出来的值
    onChange: PropTypes.func, // 监听值变化
};

export default AjaxInputSearch;
